package com.gugee.tiktok.data.consumer.blogger.core.main;

import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.tiktok.common.model.spider.aweme.Aweme_list;
import com.gugee.tiktok.common.model.spider.aweme.BloggerAwemesResponse;
import com.gugee.tiktok.data.consumer.blogger.config.DataConsumerConfig;
import com.gugee.tiktok.data.consumer.blogger.core.service.CollectService;
import com.gugee.tiktok.data.consumer.blogger.core.spider.AwemeSpiderClient;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: luolifeng
 * Date: 2020-10-14 18:29
 */
@Slf4j
@Component
public class SaveBloggerAwemeMainAsyn {

    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;

    @Autowired
    AwemeSpiderClient awemeSpiderClient;

    @Autowired
    SaveAwemeEventMain saveAwemeEventMain;

    private ThreadPoolExecutor awemeSavePoolMain;

    @Autowired
    CollectService collectService;

    @Value(value="${tiktok.data.threadpools.aweme.corePollSize}")
    int corePollSize;
    @Value(value="${tiktok.data.threadpools.aweme.queueSize}")
    int queueSize;
    @Autowired
    ScheduleTemplate scheduleTemplate;
    @Autowired
    DataConsumerConfig dataConsumerConfig;

    public void handle(String bloggerType,List<Long> uids) {
        long start = System.currentTimeMillis();
         uids.forEach(uid -> {
            try {
                handle(bloggerType,uid);
            } catch (Exception ex) {
                ex.printStackTrace();
                log.error("SaveBloggerAweme error. uid:" + uid+ex.getMessage());
            }
        });
    }
    @PostConstruct
    public void init() {
        log.info("SaveBloggerAwemeMain  init");

        awemeSavePoolMain = scheduleTemplate.getCustomThreadPool("awemeSavePool", corePollSize, corePollSize, 0, queueSize, TimeUnit.MINUTES);
    }
    public void handle(String bloggerType,long uid) {
        long max_cursor = 0;
        int count = 40;
        boolean isHasMore = true;
//        List<Aweme_list> awemes = new ArrayList<>();
        long totalStart = System.currentTimeMillis();
        int totals=0;
        Collection<Future<?>> futures = new LinkedList<Future<?>>();
        try {
            long condition = DateTimeUtils.second(LocalDateTime.now().minusDays(92));

            while (isHasMore) {
                List<Aweme_list> awemes = new ArrayList<>();
                long start = System.currentTimeMillis();
                BloggerAwemesResponse response = awemeSpiderClient.getBloggerAwemes(uid, max_cursor, count);
                if (response == null || CollectionUtils.isEmpty(response.getAweme_list())) break;
                isHasMore = response.isHas_more();
                max_cursor = response.getMax_cursor();
                //如果属于最近90天的列表则收录
                awemes.addAll(response.getAweme_list().stream()
                        .filter(a -> a.getCreate_time() > condition)
                        .collect(Collectors.toList()));
                totals=totals+awemes.size();
                //


                try {
                    futures.add(awemeSavePoolMain.submit(() -> saveAwemeEventMain.handle(bloggerType,uid, awemes)));
                } catch (Exception ex) {
                    log.error("awemeSavePoolMain error. uid:" + uid+":"+ex.getMessage());
                }
                //awemeSpiderClient.getBloggerAwemes，目前response.getMax_cursor()最多返回33个，count大于33不起效果
                if (response.getMax_cursor() <= condition * 1000) {
                    break;
                }
            }
            if((System.currentTimeMillis()-totalStart)/1000>dataConsumerConfig.getDebugTimeLimit()) {
                log.info("SaveBloggerAwemeEventListener blogger: " + uid + " ,awemes.size="+totals+", 爬取视频花费:" + (System.currentTimeMillis() - totalStart) / 1000 + "s");
            }

        } catch (Exception ex) {
            //记录异常，继续进行接下去的操作
            log.error(" uid:" + uid + " count:" + totals+ ":"+ex.getMessage());
//            ex.printStackTrace();

        }
//
//        if (awemes.size() > 0) {
//            saveAwemeEventMain.handle(bloggerType,uid, awemes,SaveAwemeEventMain.RefreshAwemeCommentType.IGNORE);
//        }else{
////            log.error(" 无视频Spider uid:" + uid + " spiderFails:" + spiderFails);
//
//        }
        //log.info(event.getSource() + " uid:" + uid + " count:" + awemes.size());



        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();

            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
